#include "logger.h"
#include <log4cpp/Category.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/FileAppender.hh>
#include <log4cpp/Priority.hh>
#include <log4cpp/RollingFileAppender.hh>
using namespace log4cpp;
//初始静态成员
Logger*Logger::_pInstance = nullptr;   

Logger::Logger()
:_root(Category::getRoot())
{

    //创建OstreamAppender (输出到控制台,和文件)
    OstreamAppender *osAppender = new OstreamAppender("console",&cout);

    //滚动日志(ERROR/WARN)
    RollingFileAppender *rollfileAppender = new RollingFileAppender("Rollingfile",
                                                                    "error_roll.log",
                                                                    1024*1024,//1Mb
                                                                    9);//保留九个文件
    rollfileAppender->setThreshold(Priority::WARN);//只接受WARN和ERROR
   
    //级别依次增加 DEBUG INFO WARN ERROR

    //普通日志文件(DEBUG)
    FileAppender *debugAppender = new FileAppender("debugfile","debug.log");
    debugAppender->setThreshold(Priority::DEBUG);
    //普通日志文件(INFO)
    FileAppender *infoAppender = new FileAppender("infofile","info.log");
    infoAppender->setThreshold(Priority::INFO);
    
    //设置布局格式
    PatternLayout* osLayout= new PatternLayout();
    PatternLayout* rollLayout= new PatternLayout();
    PatternLayout* debugLayout= new PatternLayout();
    PatternLayout* infoLayout= new PatternLayout();

    osLayout->setConversionPattern("%d %c [%p] %m%n");
    rollLayout->setConversionPattern("%d %c [%p] %m%n");
    debugLayout->setConversionPattern("%d %c [%p] %m%n");
    infoLayout->setConversionPattern("%d %c [%p] %m%n");
    
    //应用布局
    osAppender->setLayout(osLayout);
    rollfileAppender->setLayout(rollLayout);
    debugAppender->setLayout(debugLayout);
    infoAppender->setLayout(infoLayout);

    //绑定到根配置器 root Category
    _root.addAppender(osAppender);
    _root.addAppender(rollfileAppender);
    _root.addAppender(debugAppender);
    _root.addAppender(infoAppender);

    _root.setPriority(Priority::DEBUG);//全局最低级别
}

//清理log4cpp资源
Logger::~Logger(){
    Category::shutdown();
}

Logger* Logger::getInstance(){
    if(!_pInstance){
        _pInstance = new Logger();
    }
    return _pInstance;
}

void Logger::destory(){
    if(_pInstance){
        delete _pInstance;
        _pInstance = nullptr;
    }
}

//日志输入实现
void Logger::warn(const char *file,int line,const char *func, const char *msg){
    _root.warn("[文件名:%s,行号:%d,函数:(%s)]: %s",file,line,func,msg);
}

void Logger::error(const char *file,int line,const char *func, const char *msg){
    _root.error("[文件名:%s,行号:%d,函数:(%s)]: %s",file,line,func,msg);
}

void Logger::debug(const char *file,int line,const char *func, const char *msg){
    _root.debug("[文件名:%s,行号:%d,函数:(%s)]: %s",file,line,func,msg);
}

void Logger::info(const char *file,int line,const char *func, const char *msg){
    _root.info("[文件名:%s,行号:%d,函数:(%s)]: %s",file,line,func,msg);
}
